package com.personal.system.service.impl.content.web;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.personal.common.result.Result;
import com.personal.system.config.SecurityUtil;
import com.personal.system.constant.MessageConstant;
import com.personal.system.entity.content.Followed;
import com.personal.system.exception.GlobalException;
import com.personal.system.listener.SystemNoticeHandle;
import com.personal.system.mapper.content.FollowedMapper;
import com.personal.system.service.content.web.ApiFollowedService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class ApiFollowedServiceImpl implements ApiFollowedService {

    private final FollowedMapper followedMapper;

    private final SecurityUtil securityUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertFollowed(String userId) {
        String user = securityUtil.checkLogin();
        if (StrUtil.isBlank(userId)) {
            throw new GlobalException(404,"被关注用户id不能为空！");
        }
        if (userId.equals(user)) {
            throw new GlobalException(404,"不能关注自己哦！");
        }
        Followed followed = Followed.builder().userId(user).followedUserId(userId).build();
        followedMapper.insert(followed);
        // 发送系统通知
        SystemNoticeHandle.sendNotice(userId, MessageConstant.MESSAGE_WATCH_NOTICE,MessageConstant.SYSTEM_MESSAGE_CODE,null,null,null);
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteFollowed(String userId) {
        String user = securityUtil.checkLogin();
        if (StrUtil.isBlank(userId)) {
            throw new GlobalException(404,"被关注用户id不能为空！");
        }
        followedMapper.delete(new LambdaQueryWrapper<Followed>()
                .eq(Followed::getUserId,user).eq(Followed::getFollowedUserId,userId));
        return Result.ok();
    }
}